const App = getApp()
const db = wx.cloud.database()
const _ = db.command
const pages = getCurrentPages()
let that
Page({

  /**
   * 页面的初始数据
   */
  data: {
    value: "",
    show: false,
    // 搜索同学弹窗
    searchShow: false,
    searchValue: null,
    searchNum: 0,
    // 身份信息
    identityArray: [{
      name: '学生',
      id: 'Students'
    }, {
      name: '教师',
      id: 'Teachers'
    }, {
      name: '管理员',
      id: 'Administrator'
    }],
    // 传值过来的班级id
    myclassId: "",
    // 班级数组
    myclass: [],
    // 班级成员数组
    myclasslist: [],
    // 搜索使用的临时数组
    templist: [],

    // 添加搜索到的同学
    searchMember: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    that = this
    let UserInfo = App.cache.getUserInfo()
    console.log('获取用户信息:', UserInfo);
    delete UserInfo._id
    that.setData({
      UserInfo: UserInfo,
      myclassId: JSON.parse(decodeURIComponent(options.passData))
    })
    that.getmyclass()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    that.getmyclass()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  //打开搜索同学弹窗
  searchshowPopup(e) {
    this.setData({
      searchShow: true,
    });
  },
  // 关闭搜索同学弹窗
  onCloseSearch() {
    this.setData({
      searchShow: false
    });
  },
  // 搜索同学
  onSearch() {
    console.log(that.data.searchValue);
    let searchValue = Number(that.data.searchValue)
    App.toast.showLoading('搜索中')
    db.collection('userInfo').where({
        account: searchValue
      })
      .get({
        success: function (res) {
          App.toast.hideLoading()
          console.log(res.data)
          that.setData({
            searchMember: res.data,
            searchNum: 1
          })
        }
      })
  },
  // 搜索输入时的变化值
  onChange(e) {
    console.log(e.detail);
    if (e.detail === '') {
      that.setData({
        searchMember: [],
        searchNum: 0
      });
    } else {
      that.setData({
        searchValue: e.detail,
      });
    }

  },


  //打开操作面板
  showPopup(e) {
    console.log(e.currentTarget.dataset.account);
    let Infoaccount = e.currentTarget.dataset.account
    let myclass = that.data.myclasslist
    let classInfo = myclass.filter(n => n.account == Infoaccount)
    console.log('有吗', classInfo[0]);
    this.setData({
      show: true,
      classInfo: classInfo[0],
    });
  },
  // 关闭操作面板
  onClose() {
    this.setData({
      show: false
    });
  },

  // 搜索班级
  searchMyclass(e) {
    let key = e.detail.toLowerCase();
    console.log(key);
    let list = this.data.templist;
    let MyclassArray = []
    for (let i = 0; i < list.length; i++) {
      let listname = list[i].nickName.toLowerCase();
      if (listname.search(key) != -1) {
        MyclassArray.push(list[i])
      }
    }
    console.log('筛选后:', MyclassArray);
    that.setData({
      myclasslist: MyclassArray
    })
  },
  // 根据班级id获取班级详情
  getmyclass() {
    App.toast.showLoading('加载中')
    db.collection('myclass').where({
        myclassId: that.data.myclassId
      })
      .get({
        success: function (res) {
          console.log('获取班级详情', res.data[0])
          let classArrlist = res.data[0].list
          let classArr = res.data[0]
          // 根据身份id获取对应的身份
          let identityobj = that.data.identityArray
          for (let i = 0; i < classArrlist.length; i++) {
            let obj = identityobj.find(function (x) {
              return classArrlist[i].identityId === x.id
            })
            classArrlist[i].identityId = obj.name
          }
          that.setData({
            myclass: classArr,
            myclasslist: classArrlist,
            templist: classArrlist,
          })
          App.toast.hideLoading()
        }
      })
    App.toast.hideLoading()
  },
  // 移除成员
  removeMember(e) {
    let accountkey = String(e.currentTarget.dataset.account)
    accountkey = Number(accountkey)
    console.log(accountkey);
    if (accountkey == that.data.UserInfo.account) {
      App.toast.showToast('不可以移出自己，请通过退出班级来移出', 'none')
    } else {
      wx.showModal({
        title: '提示',
        content: '确定将此同学移出班级吗',
        success(res) {
          if (res.confirm) {
            App.toast.showLoading('加载中')
            db.collection('myclass').doc(that.data.myclass._id).update({
              data: {
                list: _.pull({
                  account: _.eq(accountkey),
                })
              },
              success: async function (res) {
                console.log(res)
                // 同时将这名成员从班级社区中清除
                await db.collection('chat-msg').where({
                  ChatCommunityId: 'chat' + that.data.myclass.myclassId
                }).update({
                  data: {
                    members: _.pull({
                      account: _.eq(accountkey),
                    })
                  },
                  success: function (res) {
                    console.log(res);
                  }
                })
                // 同时更新课程成员
                await db.collection('course').where({
                  'class.classId': that.data.myclass.myclassId
                }).update({
                  data: {
                    courseMember: _.pull({
                      account: _.eq(accountkey),
                    })
                  },
                  success: function (res) {
                    console.log(res);
                    App.toast.hideLoading()
                    App.toast.showToast('移出成功', 'none')
                    that.onClose()
                    that.getmyclass()
                  }
                })
              }
            })
          } else if (res.cancel) {
            App.toast.showToast('吓死我啦', 'error')
          }
          App.toast.hideLoading()
        }
      })
    }

  },

  // 添加同学
  addMember(e) {
    let member = e.currentTarget.dataset.member
    console.log(member);
    let classDetails = that.data.myclass
    console.log('classDetails', classDetails);
    let value = classDetails.list.some(item => {
      return item.account === member.account
    })
    if (!value) {
      App.toast.showLoading('添加中')
      db.collection('myclass').doc(classDetails._id).update({
        data: {
          list: _.push(member)
        },
        success: async function (res) {
          console.log(res)
          // 更新社区
          await db.collection('chat-msg').where({
            ChatCommunityId: 'chat' + classDetails.myclassId
          }).update({
            data: {
              members: _.push(member)
            },
            success: function (res) {
              console.log(res);
            }
          })
          // 同时更新课程成员
          await db.collection('course').where({
            'class.classId': that.data.myclass.myclassId
          }).update({
            data: {
              courseMember: _.push(member)
            },
            success: function (res) {
              App.toast.hideLoading()
              console.log('邀请成功', res);
              App.toast.showToast('添加成功', 'success')
              that.getmyclass()
              that.setData({
                searchValue: "",
                searchMember: [],
                searchNum: 0
              })
            }
          })
        }
      })
    } else {
      App.toast.showToast('该成员已在本班级!')
    }
  },
})